import { Reducer, Effect, Subscription } from 'umi'
import { getOptions, editRecord, addRecord } from './service'

interface UserModalType {
    namespace: 'users';
    state: {};
    reducers: {
        getList: Reducer
    };
    effects: {
        getRemote: Effect,
        edit: Effect,
        add: Effect,
    };
    subscriptions: {
        setup: Subscription
    };

}

const UserModal: UserModalType = {
    namespace: 'users',
    state: {},//初始值
    reducers: {
        getList: (state: any, { payload }) => {

            return { ...payload };
        }
    },
    effects: { //无返回值 用来处理异步
        *getRemote(action, { put, call }) {

            const data = yield call(getOptions);

            yield put({
                type: 'getList',
                payload: data
            });
        },
        *edit({ payload: { id, val } }, { put, call }) {
            const data = yield call(editRecord, { id, val });
            yield put({
                type: 'getRemote'
            })
        },
        *add({ payload: { val } }, { put, call }) {
            const data = yield call(addRecord, { val });
            yield put({
                type: 'getRemote'
            })
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                if (pathname === '/users') {
                    dispatch({
                        type: 'getRemote'
                    });
                }
            });
        }
    },
}
export default UserModal;